<template>
  <div>
    <el-card class="box-card">
      <h2>二维码登录</h2>
      
      <!-- 二维码显示区域 -->
      <div class="qr-container" v-if="!loginSuccess">
        <div v-if="qrCodeImage" class="qr-image-container">
          <img :src="qrCodeImage" alt="二维码" class="qr-image" />
          <p class="qr-status">{{ statusMessage }}</p>
        </div>
        
        <div v-else class="loading-container">
          <el-icon class="is-loading"><Loading /></el-icon>
          <p>正在生成二维码...</p>
        </div>
        
        <!-- 刷新按钮 -->
        <div class="refresh-container">
          <el-button @click="generateQrCode" :loading="generating">
            刷新二维码
          </el-button>
        </div>
      </div>
      
      <!-- 登录成功显示 -->
      <div v-else class="success-container">
        <el-icon class="success-icon"><CircleCheckFilled /></el-icon>
        <h3>登录成功！</h3>
        <p>欢迎回来，{{ userInfo.name }}</p>
        <el-button type="primary" @click="goToHome">进入系统</el-button>
      </div>
      
      <!-- 返回普通登录 -->
      <div class="back-login">
        <router-link to="/login">
          <el-button>返回普通登录</el-button>
        </router-link>
      </div>
    </el-card>
  </div>
</template>

<script>
import { Loading, CircleCheckFilled } from '@element-plus/icons-vue'

export default {
  name: 'QrLogin',
  components: {
    Loading,
    CircleCheckFilled
  },
  data() {
    return {
      qrCodeImage: '',
      qrToken: '',
      statusMessage: '等待扫码...',
      generating: false,
      loginSuccess: false,
      userInfo: {},
      pollingInterval: null
    }
  },
  mounted() {
    this.generateQrCode()
  },
  beforeUnmount() {
    this.stopPolling()
  },
  methods: {
    // 生成二维码
    async generateQrCode() {
      this.generating = true
      this.qrCodeImage = ''
      this.statusMessage = '正在生成二维码...'
      
      try {
        const response = await this.$axios.post('/api/qr/generate')
        
        if (response.data.code === '0') {
          // 直接使用后端生成的二维码图片（已包含ngrok地址）
          this.qrCodeImage = response.data.data.qrCodeImage
          this.qrToken = response.data.data.token
          this.statusMessage = '请使用手机扫描二维码登录'
          this.startPolling()
          
          // 在控制台输出完整URL，方便调试
          console.log('二维码完整URL:', response.data.data.qrContent)
        } else {
          this.$message.error(response.data.msg || '生成二维码失败')
        }
      } catch (error) {
        console.error('生成二维码失败:', error)
        this.$message.error('生成二维码失败，请重试')
      } finally {
        this.generating = false
      }
    },
    
    // 开始轮询检查状态
    startPolling() {
      this.stopPolling() // 先停止之前的轮询
      this.pollingInterval = setInterval(() => {
        this.checkQrStatus()
      }, 2000) // 每2秒检查一次
    },
    
    // 停止轮询
    stopPolling() {
      if (this.pollingInterval) {
        clearInterval(this.pollingInterval)
        this.pollingInterval = null
      }
    },
    
    // 检查二维码状态
    async checkQrStatus() {
      if (!this.qrToken) return
      
      try {
        const response = await this.$axios.get(`/api/qr/status/${this.qrToken}`)
        if (response.data.code === '0') {
          const qrToken = response.data.data
          
          if (qrToken.status === 'CONFIRMED') {
            // 二维码已确认，获取用户信息
            await this.getUserInfo()
          } else if (qrToken.status === 'EXPIRED') {
            this.statusMessage = '二维码已过期，请刷新'
            this.stopPolling()
          } else {
            this.statusMessage = '等待扫码确认...'
          }
        } else if (response.data.code === '2003') {
          this.statusMessage = '二维码已过期，请刷新'
          this.stopPolling()
        }
      } catch (error) {
        console.error('检查二维码状态失败:', error)
      }
    },
    
    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await this.$axios.get(`/api/qr/user/${this.qrToken}`)
        if (response.data.code === '0') {
          this.userInfo = response.data.data
          this.loginSuccess = true
          this.stopPolling()
          
          // 保存用户信息到sessionStorage
          sessionStorage.setItem("user", JSON.stringify(this.userInfo))
          
          this.$message.success('登录成功！')
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.$message.error('获取用户信息失败')
      }
    },
    
    // 跳转到首页
    goToHome() {
      this.$router.push('/home')
    }
  }
}
</script>

<style scoped>
.box-card {
  margin: auto auto;
  width: 400px;
  text-align: center;
}

.qr-container {
  padding: 20px 0;
}

.qr-image-container {
  margin-bottom: 20px;
}

.qr-image {
  width: 200px;
  height: 200px;
  border: 1px solid #ddd;
  border-radius: 8px;
}


.qr-status {
  margin: 5px 0;
  color: #409eff;
  font-size: 14px;
  font-weight: bold;
}

.loading-container {
  padding: 40px 0;
  color: #666;
}

.loading-container .el-icon {
  font-size: 24px;
  margin-bottom: 10px;
}

.refresh-container {
  margin-top: 20px;
}

.success-container {
  padding: 40px 0;
}

.success-icon {
  font-size: 48px;
  color: #67c23a;
  margin-bottom: 20px;
}

.success-container h3 {
  color: #67c23a;
  margin-bottom: 10px;
}

.back-login {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}
</style> 